package com.asset.web.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.logout.LogoutFilter;

/**
 * @author 11725
 */
public class LoginConfigurer<T extends LoginConfigurer<T, B>, B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T, B>  {

    private MyUsernamePasswordAuthenticationFilter authFilter;

    public LoginConfigurer() {
        this.authFilter = new MyUsernamePasswordAuthenticationFilter();
    }

    @Override
    public void configure(B http) throws Exception {
        // 设置 Filter 使用的 AuthenticationManager, 这里取公共的即可
        authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        // 设置登录成功的 Handler
        authFilter.setAuthenticationSuccessHandler(new LoginSuccessHandler());

        // 设置失败的 Handler
        authFilter.setAuthenticationFailureHandler(new LoginFailureHandler());

        // 不将认证后的context放入session
        //        authFilter.setSessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());

        MyUsernamePasswordAuthenticationFilter filter = this.postProcess(authFilter);
        //指定 Filter 的位置
        http.addFilterAfter(filter, LogoutFilter.class);
    }
}
